<template>
  <doc-alert title="【产品】产品 SPU 与 SKU" url="https://doc.iocoder.cn/mall/product-spu-sku/" />

  <ContentWrap>
    <div :class="searchVisible ? 'flex flex-row flex-wrap mb-2' : 'flex flex-row flex-wrap'">
      <el-button v-if="showBack" @click="router.back()">
        <Icon icon="ep:arrow-left" class="mr-5px" />
        返回
      </el-button>
      <el-button plain type="primary" @click="openForm(undefined)" v-hasRole="['shop_admin']">
        <Icon class="mr-5px" icon="ep:plus" />
        新增
      </el-button>
      <el-button plain type="success" @click="searchVisible = !searchVisible">
        <Icon class="mr-5px" icon="ep:operation" />
        {{ searchVisible ? '关闭筛选' : '打开筛选' }}
      </el-button>
      <el-text type="info">
        <span class="ml-5px">{{ searchVisible ? '关闭以下筛选条件' : '点击打开筛选条件' }}</span>
      </el-text>
      <div class="flex-1"></div>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh" />
        刷新列表
      </el-button>
    </div>
    <el-form
      v-if="searchVisible"
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入产品名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行业类目" prop="platformCategoryId">
        <el-cascader
          v-model="queryParams.platformCategoryId"
          :options="platformCategoryTree"
          :props="strictlyProps"
          class="w-1/1"
          :filterable="false"
          :clearable="true"
          node-key="id"
          placeholder="请选择行业类目"
        />
      </el-form-item>
      <el-form-item label="店铺" prop="shopId" v-hasRole="['super_admin']">
        <el-cascader
          v-model="queryParams.shopId"
          :options="shopList"
          :props="defaultProps"
          class="w-1/1"
          :filterable="false"
          :clearable="true"
          node-key="id"
          placeholder="请选择店铺"
        />
      </el-form-item>
      <!-- <el-form-item label="品牌" prop="brandId">
        <el-cascader
          v-model="queryParams.brandId"
          :options="brandList"
          :props="defaultProps"
          class="w-1/1"
          :filterable="false"
          :clearable="true"
          node-key="id"
          placeholder="请选择品牌"
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button
          v-hasPermi="['product:spu:export']"
          :loading="exportLoading"
          plain
          type="success"
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <slot name="tabs-top"></slot>
    <el-tabs v-model="queryParams.tabType" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="item in tabsData"
        :key="item.type"
        :label="item.name + '(' + item.count + ')'"
        :name="item.type"
      />
    </el-tabs>
    <el-table v-loading="loading" :data="list">
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-form class="spu-table-expand" label-position="left">
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="销售价:">
                      <span>¥{{ fenToYuan(row.price) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="成本价:">
                      <span>¥{{ fenToYuan(row.costPrice) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="会员价:">
                      <span>¥{{ fenToYuan(row.vipPrice) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="联盟豆:">
                      <span
                        >{{ row.cryptocurrencyDeductCount }}个抵扣¥{{
                          fenToYuan(row.cryptocurrencyDeductPrice)
                        }}</span
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="品牌:">
                      <span>{{ row.brandName || '不详' }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="推荐类型:">
                      <span v-if="row.recommend == 0">不推荐</span>
                      <span v-else-if="row.recommend == 1">热卖</span>
                      <span v-else-if="row.recommend == 2">精选</span>
                      <span v-else-if="row.recommend == 3">上新</span>
                      <span v-else-if="row.recommend == 4">补贴</span>
                      <span v-else>未知</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="浏览量:">
                      <span>{{ row.browseCount }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="起购数量:">
                      <span
                        >{{ (row.limitMinQuantity || 1) * (row.stepQuantity || 1)
                        }}{{ row.unitName || '' }}</span
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="产品信息" min-width="200">
        <template #default="{ row }">
          <div class="flex">
            <el-image
              fit="cover"
              :src="row.picUrl"
              :preview-src-list="[row.picUrl]"
              :initial-index="0"
              :preview-teleported="true"
              :hide-on-click-modal="true"
              class="flex-none w-50px h-50px"
            />
            <div class="flex" style="flex-direction: column">
              <div class="ml-4 using-hidden">
                <el-tooltip effect="dark" :content="row.name" placement="top">
                  {{ row.name }}
                </el-tooltip>
              </div>
              <div v-if="row.priceMode === 2" class="ml-4 color-red">称重</div>
              <div v-else-if="row.price === 0" class="ml-4 color-red">免费</div>
              <div v-else class="ml-4 color-red">¥ {{ fenToYuan(row.price) }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="所属店铺"
        align="left"
        prop="shopInfo"
        min-width="150"
        v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
      >
        <template #default="scope">
          <div class="flex items-center">
            <el-image
              fit="cover"
              :src="scope.row.shop?.logo || '/placeholder.png'"
              :preview-src-list="[scope.row.shop?.logo || '/placeholder.png']"
              :initial-index="0"
              :preview-teleported="true"
              :hide-on-click-modal="true"
              class="flex-none w-30px h-30px"
            />
            <span class="ml-[10px] multi-hidden" :title="scope.row.shop?.name || '未知'">{{
              scope.row.shop?.name || '未知'
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="分类信息" min-width="150">
        <template #default="{ row }">
          <el-text>{{ formatPlatformCategoryName(row.platformCategoryId) }}</el-text>
          <br />
          <el-text>{{ formatCategoryName(row.categoryId) }}</el-text>
          <br />
        </template>
      </el-table-column>
      <el-table-column align="left" label="其他信息" min-width="130">
        <template #default="{ row }">
          <el-text
            >真实销量：{{ (row.salesCount || 0) * (row.stepQuantity || 1) }}{{ row.unitName || '' }}
          </el-text>
          <br />
          <el-text
            >虚拟销量：{{ (row.virtualSalesCount || 0) * (row.stepQuantity || 1)
            }}{{ row.unitName || '' }}
          </el-text>
          <br />
          <el-text
            >库存：{{ (row.stock || 0) * (row.stepQuantity || 1) }}{{ row.unitName || '' }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="left" label="状态" min-width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status < 0" type="info">回收站</el-tag>
          <div v-else>
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="已上架"
              inactive-text="已下架"
              inline-prompt
              @change="handleStatusChange(row)"
              v-hasPermi="['product:spu:update']"
            />
            <br v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']" />
            <el-switch
              v-model="row.isSticky"
              :active-value="true"
              :inactive-value="false"
              active-text="已置顶"
              inactive-text="未置顶"
              inline-prompt
              @change="handleStickyChange(row)"
              v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
            />
            <br v-hasRole="['shop_admin']" />
            <el-switch
              v-model="row.isSticky"
              disabled
              :active-value="true"
              :inactive-value="false"
              active-text="已置顶"
              inactive-text="未置顶"
              inline-prompt
              v-hasRole="['shop_admin']"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
        sortable
      />
      <el-table-column align="center" fixed="right" label="操作" min-width="150">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="openDetail(row.id)"
            v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm(row.id)"
            v-hasPermi="['product:spu:update']"
          >
            修改
          </el-button>
          <el-button
            link
            type="warning"
            @click="openSortForm(row.id)"
            v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
          >
            排序
          </el-button>
          <template v-if="queryParams.tabType === 'RECYCLE_BIN'">
            <el-button link type="danger" @click="handleDelete(row.id)" v-hasRole="['shop_admin']">
              删除
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleStatus02Change(row, ProductSpuStatusEnum.DISABLE.status)"
              v-hasRole="['shop_admin']"
            >
              恢复
            </el-button>
          </template>
          <template v-else>
            <el-button
              :disabled="row.status < 0"
              link
              type="danger"
              @click="handleStatus02Change(row, ProductSpuStatusEnum.RECYCLE.status)"
              v-hasRole="['shop_admin']"
            >
              回收
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" setup name="TableList">
import { dateFormatter } from '@/utils/formatTime'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import { ShopCategoryApi } from '@/api/mall/shop/category'
import * as ProductSpuApi from '@/api/mall/product/spu'
// import * as ProductBrandApi from '@/api/mall/product/brand'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { ShopInfoApi } from '@/api/mall/shop/info'
import { TabsPaneContext } from 'element-plus'
// import {getCategorySimpleList} from "@/api/mall/product/category";

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute() // 路由
const router = useRouter()
const searchVisible = ref(false)

const strictlyProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: false,
  multiple: false,
  checkStrictly: true
}

const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据

const tabsData = ref<any>([
  {
    name: '全部',
    type: 'ALL',
    count: 0
  },
  {
    name: '出售中',
    type: 'FOR_SALE',
    count: 0
  },
  {
    name: '仓库中',
    type: 'IN_WAREHOUSE',
    count: 0
  },
  {
    name: '已售罄',
    type: 'SOLD_OUT',
    count: 0
  },
  {
    name: '警戒库存',
    type: 'ALERT_STOCK',
    count: 0
  },
  {
    name: '回收站',
    type: 'RECYCLE_BIN',
    count: 0
  }
])

const queryParams = ref<any>({
  pageNo: 1,
  pageSize: 10,
  type: '',
  tabType: 'ALL',
  name: '',
  platformCategoryId: '',
  shopId: '',
  categoryId: '',
  brandId: '',
  createTime: []
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductSpuApi.getSpuPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const openList = async (type?: string | number) => {
  queryParams.value.type = type
  console.log('type=' + type)
  getTabsCount()
  await getList()
}

defineExpose({
  openList
})

const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName
  console.log('tabType=' + tab.paneName)
  getTabsCount()
  getList()
}

/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
  const tabsCount = await ProductSpuApi.getTabsCount(queryParams.value.type)
  //console.log("tabsCount=" + JSON.stringify(tabsCount))
  //console.log("tabsData=" + JSON.stringify(tabsData.value))
  for (let index in tabsData.value) {
    let tabItem = tabsData.value[index]
    tabItem.count = Number(tabsCount[tabItem?.type])
  }
  tabsData.value[0].count = Number(tabsCount['FOR_SALE']) + Number(tabsCount['IN_WAREHOUSE'])
  //console.log("newTabsData=" + JSON.stringify(tabsData.value))
}

/** 添加到仓库 / 回收站的状态 */
const handleStatus02Change = async (row: any, newStatus: number) => {
  try {
    // 二次确认
    const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
    await message.confirm(`确认要"${row.name}"${text}吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ id: row.id, status: newStatus })
    message.success(text + '成功')
    // 刷新 tabs 数据
    getTabsCount()
    // 刷新列表
    await getList()
  } catch {}
}

/** 更新上架/下架状态 */
const handleStatusChange = async (row: any) => {
  try {
    // 二次确认
    const text = row.status ? '上架' : '下架'
    await message.confirm(`确认要${text}"${row.name}"吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ id: row.id, status: row.status })
    message.success(text + '成功')
    // 刷新 tabs 数据
    getTabsCount()
    // 刷新列表
    await getList()
  } catch {
    // 异常时，需要重置回之前的值
    row.status =
      row.status === ProductSpuStatusEnum.DISABLE.status
        ? ProductSpuStatusEnum.ENABLE.status
        : ProductSpuStatusEnum.DISABLE.status
  }
}

/** 更新置顶 */
const handleStickyChange = async (row: any) => {
  try {
    // 二次确认
    const text = row.isSticky ? '置顶' : '取消置顶'
    await message.confirm(`确认要${text}"${row.name}"吗？`)
    // 发起修改
    await ProductSpuApi.updateSticky({ id: row.id, isSticky: row.isSticky })
    message.success(text + '成功')
    // 刷新 tabs 数据
    getTabsCount()
    // 刷新列表
    await getList()
  } catch {
    // 异常时，需要重置回之前的值
    row.isSticky = !row.isSticky
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number | string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductSpuApi.deleteSpu(id)
    message.success(t('common.delSuccess'))
    // 刷新tabs数据
    getTabsCount()
    // 刷新列表
    await getList()
  } catch {}
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增或修改 */
const openForm = (id?: number | string) => {
  // 修改
  if (id) {
    router.push({ name: 'ProductSpuEdit', params: { id } })
    return
  }
  // 新增
  router.push({ name: 'ProductSpuAdd' })
}

/** 排序及推荐 */
const recommendSortFormRef = ref()
const openSortForm = (id?: number | string) => {
  recommendSortFormRef.value.open(id)
}

/** 查看产品详情 */
const openDetail = (id: number | string) => {
  router.push({ name: 'ProductSpuDetail', params: { id } })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSpuApi.exportSpu(queryParams.value)
    download.excel(data, '产品列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分类的节点的完整结构 */
const platformCategoryTree = ref()
const formatPlatformCategoryName = (categoryId: string) => {
  if (categoryId == '0') {
    return '行业类目不详'
  }
  return treeToString(platformCategoryTree.value, categoryId)
}
const productCategoryTree = ref()
const formatCategoryName = (categoryId: string) => {
  if (categoryId == '0') {
    return '产品分类不详'
  }
  return treeToString(productCategoryTree.value, categoryId)
}
//const brandList = ref()
const shopList = ref()

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
const showBack = ref(false)
onMounted(async () => {
  if (route.query.platformCategoryId) {
    queryParams.value.platformCategoryId = route.query.platformCategoryId + ''
    showBack.value = true
  }
  if (route.query.categoryId) {
    queryParams.value.categoryId = route.query.categoryId + ''
    showBack.value = true
  }
  if (route.query.brandId) {
    queryParams.value.brandId = route.query.brandId + ''
    showBack.value = true
  }
  getTabsCount().then(() => {})
  // 获得产品信息
  await getList()
  // 获得分类树
  ShopCategoryApi.getShopCategoryList({}).then((res) => {
    platformCategoryTree.value = handleTree(res, 'id', 'parentId')
  })
  ProductCategoryApi.getCategorySimpleList().then((res) => {
    productCategoryTree.value = handleTree(res, 'id', 'parentId')
  })
  //ProductBrandApi.getSimpleBrandList().then((res) => {
  //  brandList.value = res
  //})
  ShopInfoApi.getShopInfoSimpleList().then((res) => {
    shopList.value = res
  })
})
</script>

<style lang="scss" scoped>
.spu-table-expand {
  padding-left: 42px;

  :deep(.el-form-item__label) {
    width: 82px;
    font-weight: bold;
    color: #99a9bf;
  }
}
</style>
